/*
 * 封装axios请求
 * 对错误的统一处理
 */
import errorHandle from './errorHandle';
import axios from 'axios';
import { ElMessageBox } from 'element-plus';
let showReLogDialog = false;
class httpRequest {
  constructor(baseUrl) {
    this.baseUrl = baseUrl;
    this.pending = {};
  }
  // 获取实例配置
  getInsitConfig() {
    const config = {
      baseURL: this.baseUrl,
      timeout: 600000,
      headers: {
        'Content-Type': 'application/json;chartset=utf-8',
        // 'X-Forwarded-For':'123'
      },
    };
    return config;
  }
  // 取消重复请求
  removePending(key, isRequest = false) {
    if (this.padding[key] && isRequest) {
      this.pendding[key]('取消重复请求');
    }
    delete this.padding[key];
  }

  // 请求拦截器
  intercepter(instance) {
    instance.interceptors.request.use(
      (config) => {
       
        return config;
      },
      (error) => {
        errorHandle(error);
        return Promise.reject(error);
      }
    );

    // 响应拦截器
    instance.interceptors.response.use(
      (res) => {
        if (res.status === 200) {
         
          return Promise.resolve(res.data);
        } else {
          return Promise.reject(error);
        }
      },
      (error) => {
        return Promise.reject(error);
      }
    );
  }
  // 创建实例
  request(options) {
    const instance = axios.create();
    const newOption = Object.assign(this.getInsitConfig(), options);
    this.intercepter(instance);
    return instance(newOption);
  }

  // get请求
  get(url, data, config) {
    if (data) {
      let count = 0;
      for (let i in data) {
        if (count == 0) {
          url += '?' + i + '=' + data[i];
          count++;
        } else {
          url += '&' + i + '=' + data[i];
        }
      }
    }
    const option = Object.assign(
      {
        method: 'get',
        url,
      },
      config
    );
    return this.request(option);
  }
  post(url, data, config) {
    const option = Object.assign(
      {
        method: 'post',
         responseType: 'stream',
        url,
        data:data,
      },
      config
    );
    return this.request(option);
  }
  uploadFile(url, data, config) {
    const option = Object.assign(
      {
        method: 'post',
        url,
        data:data,
      },
    );
    return this.request(option);
  }

}
export default httpRequest;
